/*
 * BtnDelete.java
 *
 * Created on June 23, 2007, 4:01 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package latihanibatis.ui.event;

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import latihanibatis.dao.MahasiswaDao;
import latihanibatis.ui.MhsTabelModel;
import latihanibatis.ui.PanelStatus;

/**
 *
 * @author javamaniac
 */
public class BtnDelete extends AbstractAction {
    
    private final MhsTabelModel tableModel;
    private final PanelStatus status;
    private final JTable tableMhs;
    private final MahasiswaDao mhsDao;
    
    /** Creates a new instance of BtnDelete */
    public BtnDelete(MhsTabelModel model, PanelStatus pnl, JTable tbl, MahasiswaDao dao) {
        
        super();
        this.tableModel = model;
        this.status     = pnl;
        this.tableMhs   = tbl;
        this.mhsDao     = dao;
    }
    
    public void actionPerformed(final ActionEvent evt) {
        final int baris  = tableMhs.getSelectedRow(); // dimulai dari 0
        final int kolom  = tableMhs.getColumnCount(); // ambil smua jml kolom.
        final int jmlBrs = tableMhs.getRowCount();    // dimulai dari 1
        
        String isiTable = "";
        int deleteNim = 0;
        if (baris < 0 || baris >= jmlBrs) {
            status.setStatus("Tidak Ada Data Yang Ingin Dihapus !!", "ERROR");            
            JOptionPane.showMessageDialog(null, "Tidak Ada Data Yang Ingin Dihapus !!");
            
            tableMhs.selectAll();
        } else {
            for (int i=baris; i == baris; i++) {
                for (int j=0; j < kolom; j++) {
                    
                    isiTable = tableModel.getValueAt(i,j).toString();
                    
                    // Ambil NIM Mhs yg akan dihapus.
                    if (j == 0)
                        deleteNim = Integer.parseInt(isiTable);
                } // end for j
            } // end for i
            
            final int resultDelet = mhsDao.deleteMhs(deleteNim);
            
            if (resultDelet == 0) {
                status.setStatus("Mahasiswa Dengan NIM " + deleteNim + " Gagal Dihapus !!",
                    "ERROR");
                
                JOptionPane.showMessageDialog(null, "Mahasiswa Dengan NIM :\n" +
                    deleteNim + " Gagal Dihapus !!");
            } else {
                tableModel.hapusDasar(baris); // Delete on JTable
                status.setStatus("Mahasiswa Dengan NIM " + deleteNim + " Berhasil Dihapus !!",
                    "SUKSES");
                
                JOptionPane.showMessageDialog(null, "Mahasiswa Dengan NIM :\n" +
                    deleteNim + " Berhasil Dihapus !!");
            }
        }
    }
}
